<?php

namespace App\Http\Controllers\OpenShop\FeishuMini;

use App\Http\Controllers\BaseController;
use App\Http\Validate\OpenShop\SiteLocation\ShopValidate;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Merchant\LogisticsService;
use App\Service\OpenShop\Merchant\OrderProgressService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Service\OpenShop\FeishuMini\ShopService;
use Illuminate\Validation\ValidationException;
use Kuafu\express\KuafuExpress;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ShopController extends BaseController
{
    public function overview(Request $request)
    {
        $userId         = getRmsUserInfoByAuth()->id;
        $dataPermission = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        if ($dataPermission == PermissionService::PERMISSION_DENY) {
            return $this->fail(1, '权限不足');
        }

        // isAll && 原生sql
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, $userId);
        $lists = (new ShopService($orderPermission))->overview();

        return $this->success(['lists' => $lists]);
    }

    public function lists(Request $request)
    {
        $search            = (string)$request->get('search');
        $pageSize          = (int)$request->get('pageSize', 20);
        $pageNum           = (int)$request->get('pageNum', 1);
        $cityCode          = (int)$request->get('cityCode');
        $signStartDate     = (string)$request->get('signStartDate'); // ymd
        $signEndDate       = (string)$request->get('signEndDate'); // ymd
        $locationStartDate = (string)$request->get('locationStartDate'); // ymd
        $locationEndDate   = (string)$request->get('locationEndDate'); // ymd
        $openingStartDate  = (string)$request->get('openingStartDate'); // ymd
        $openingEndDate    = (string)$request->get('openingEndDate'); // ymd
        $stepStatusLists   = (string)$request->get('stepStatusLists');
        if ($stepStatusLists) {
            $stepStatusLists   = explode(',', $stepStatusLists);
        } else {
            $stepStatusLists = [];
        }

        $userId         = getRmsUserInfoByAuth()->id;
        $dataPermission = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        if ($dataPermission == PermissionService::PERMISSION_DENY) {
            return $this->fail(1, '权限不足');
        }

        // isAll && 原生sql
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, $userId);

        $data = (new ShopService($orderPermission))
            ->miniShopLists($search, $cityCode, $signStartDate, $signEndDate, $locationStartDate, $locationEndDate,
                $openingStartDate, $openingEndDate, $pageSize, $pageNum, $stepStatusLists);

        return $this->success($data);
    }

    /**
     * 飞书小程序开店流程进度
     * @param Request $request
     * @return JsonResponse
     * @throws GuzzleException
     */
    public function progress(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string',
        ]);

        return $this->success((new OrderProgressService)->setOrderNo($request->get('orderNo'))->progress(OrderProgressService::PROGRESS_ORIGIN_APPLET));
    }

    public function detail(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string',
        ]);
        $orderNo  = $request->get('orderNo');
        return $this->success(ShopService::detail($orderNo));
    }

    public function logistics(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string',
        ]);
        $shopId = OpenShopMainProcessModel::query()->where('orderNo', $request->get('orderNo'))->value('shopId');
        //获得软装信息
        $softOutfit = [
            'softOutfit' => ShopService::softOutfit($request->orderNo)
        ];

        $data = LogisticsService::detail($request->orderNo, $shopId);
        if (!empty($data)) {
            if (count($data['equipments'])) {
                foreach ($data['equipments'] as $k => $equipment) {
                    if ($equipment['type'] == 2) {  //订货的 1 物流  2 快递
                        $data['equipments'][$k]['url'] = KuafuExpress::webUrl($equipment['express_code'], $equipment['provider_code']);
                    }
                }
            }
        }
        return $this->success([
            'list' => array_merge($softOutfit, $data),
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws GuzzleException
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cityShop(Request $request): JsonResponse
    {
        $params = ShopValidate::cityShopValidate($request->merge(["shopName" => $request->get('shopName', '')])->all());
        return $this->success(ShopService::cityShop($params));
    }
}
